<?php

namespace app\repository;

use catchAdmin\user\model\User;
use catcher\Code;
use catcher\exceptions\FailedException;

class UserRepository extends BaseRepository
{
    protected $model;
    public function __construct(User $model)
    {
        $this->model = $model;
    }

    /**
     * 获取微信用户信息成功后的处理
     * @param string openid
     * @param string userInfo 解密成功后的用户基础信息
     */
    public function afterWxGetUserInfo($openid, $userInfo)
    {
        $result = $this->model->where('openid', $openid)->find();
        $data = [
            'openid' => $openid,
            'name' => $userInfo['nickName'],
            'avatar_url' => $userInfo['avatarUrl'],
        ];
        if (!$result) $result['id'] = $this->model->storeBy($data);
        else $result->save($data);

        return $this->model->find($result['id']);
    }

    /**
     * 获取微信绑定的手机号成功后的处理
     * @param string openid
     * @param string purePhoneNumber 没有区号的手机号
     */
    public function afterwxGetPhoneNumber($openid, $purePhoneNumber, $auth)
    {
        $result = $this->model->field('phone,last_time')->where('openid', $openid)->find();
        $result->save([
            'phone' => $purePhoneNumber,
            'last_time' => date('Y-m-d H:i:s'),
        ]);

        try {
            $token = $auth->guard('api')->ignorePasswordVerify()->attempt(['phone' => $purePhoneNumber]);
            return [
                'token' => $token,
                'phone' => $purePhoneNumber,
                'userInfo' => $auth->user()
            ];
        } catch (\Exception $e) {
            throw new FailedException($e->getCode() == Code::USER_FORBIDDEN ? '该账户已被禁用，请联系管理员' : '登录失败，请检查手机号', Code::LOGIN_FAILED);
        }
    }
}
